import { defineStore } from 'pinia'
import { showErrorMsg, showSuccessMsg } from '@/utils/alterMessage.js'
import router from '@/router/index.js'
import $ajax from '@/api/to8060.js'
import { useStatisticsStore } from '@/stores/statistics/statistics.js'

export const useAqiFeedbackStore = defineStore('aqiFeedback', {
  state: () => ({
    aqiFeedback: {
      memId: -1,
      address: '',
      information: '',
      estimatedGrade: 0,
      province: ''
    },
    stepLength: 1,
    feedbackList: [],
    timeLineData: [],
    drawerVisible: false,
    currentAqiFeedback: {},
    btnShow: true
  }),
  actions: {
    dataInit() {
      // rgb(59 130 246) rgb(34 197 94) rgb(107 114 128)
      this.timeLineData.length = 0
      let date = this.getCurrentTime()
      this.timeLineData.push({
        timestamp: date,
        color: 'rgb(34 197 94)',
        content: '反馈提交',
        tips: '您的建议我们已经收到，请耐心等待处理结果'
      })
      this.timeLineData.push({
        timestamp: date,
        color: 'rgb(107 114 128)',
        content: '任务指派',
        tips: '我们已指派网格员进行检测'
      })
      this.timeLineData.push({
        timestamp: date,
        color: 'rgb(107 114 128)',
        content: '实地检测',
        tips: '网格员正在实地检测中，请耐心等待'
      })
      this.timeLineData.push({
        timestamp: date,
        color: 'rgb(107 114 128)',
        content: '检测成功',
        tips: '实地检测成功，感谢您的配合'
      })
    },
    getCurrentTime() {
      const now = new Date()

      const year = now.getFullYear()
      const month = ('0' + (now.getMonth() + 1)).slice(-2)
      const day = ('0' + now.getDate()).slice(-2)
      const hours = ('0' + now.getHours()).slice(-2)
      const minutes = ('0' + now.getMinutes()).slice(-2)
      const seconds = ('0' + now.getSeconds()).slice(-2)

      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
    },
    clear() {
      this.aqiFeedback.memId = -1
      this.aqiFeedback.address = ''
      this.aqiFeedback.information = ''
      this.aqiFeedback.estimatedGrade = 0
      this.aqiFeedback.province = ''
      this.stepLength = 1
      this.timeLineData.length = 0
    },
    async loadData(param) {
      this.dataInit()
      if (param === null) {
        return
      }
      this.timeLineData[0].timestamp = param.afDate
      if (param.state === 0) {
        //已提交待分配
        this.timeLineData[1].color = 'rgb(59 130 246)'
      } else if (param.state === 1) {
        // 已经分配任务待检测
        this.timeLineData[1].color = 'rgb(34 197 94)'
        this.timeLineData[2].color = 'rgb(59 130 246)'
        this.timeLineData[1].timestamp = param.assignDate
      } else if (param.state === 2) {
        // 流程结束
        this.timeLineData[1].color = 'rgb(34 197 94)'
        this.timeLineData[2].color = 'rgb(34 197 94)'
        this.timeLineData[3].color = 'rgb(34 197 94)'
        this.timeLineData[1].timestamp = param.assignDate
        const statisticsStore = useStatisticsStore()
        const statistic = await statisticsStore.getStatistic(param.afId)
        //设置时间
        this.timeLineData[2].timestamp = statistic.confirmDate
        this.timeLineData[3].timestamp = statistic.confirmDate
        //设置内容
        this.timeLineData[1].tips = `该我们已指派网格员(编号${statistic.gmId})进行检测
        `
        this.timeLineData[3].tips = `该网格区域的AQI检测结果为：
              ${statistic.aqiId}
        `
      }
    },
    dataProcess() {
      let currentUser = sessionStorage.getItem('currentUser')
      if (currentUser === null) {
        router
          .push('/login')
          .then(() => {
            showErrorMsg('请先登录')
          })
          .catch((error) => {
            console.log(error)
          })
      }
      currentUser = JSON.parse(currentUser)
      this.aqiFeedback.memId = currentUser.memId
      return currentUser.memId
    },
    async submit() {
      this.dataProcess()
      const path = '/aqiFeedback/report'
      const res = await $ajax.post(path, this.aqiFeedback)
      // console.log(res)
      if (res !== null && res.code != null && res.code === 200) {
        showSuccessMsg('反馈成功')
        setTimeout(() => {
          if (res.msg === '尚未分配网格员') {
            showErrorMsg('尚未分配网格员,请耐心等待')
          } else {
            showSuccessMsg('已分配网格员，请耐心等待检测结果')
          }
        }, 2000) // 设置延迟时间为2000毫秒（2秒）
      }
      return res !== null && res.code === 200
    },
    async getFeedbackList() {
      const memId = this.dataProcess()
      const path = '/aqiFeedback/select/ById'
      const res = await $ajax.get(path, {
        params: {
          memId: memId
        }
      })
      if (res !== null && res.code != null && res.code === 200) {
        this.feedbackList = res.result
      }
    },
    async getTaskList() {
      const path = '/aqiFeedback/select/all'
      const res = await $ajax.get(path)
      if (res !== null && res.code === 200) {
        this.feedbackList = res.result
      } else {
        showErrorMsg('获取任务列表失败')
      }
    },
    async getAssignList() {
      const path = '/aqiFeedback/select/unAssigned'
      const res = await $ajax.get(path)
      if (res !== null && res.code === 200) {
        this.feedbackList = res.result
      } else {
        showErrorMsg('获取任务列表失败')
      }
    },
    async getMyAssignList() {
      const memId = this.dataProcess()
      const path = '/aqiFeedback/select/myUnAssigned'
      const res = await $ajax.get(path, {
        params: {
          gmId: memId,
          state: 1
        }
      })
      if (res !== null && res.code === 200) {
        if (res.result.length === 0) {
          showSuccessMsg('暂无待待检测任务')
        } else {
          this.feedbackList = res.result
          showSuccessMsg('您共有' + res.result.length + '条待检测任务')
        }
      } else {
        showErrorMsg('获取任务列表失败')
      }
    },
    async getMyHistoryList() {
      const memId = this.dataProcess()
      const path = '/aqiFeedback/select/myUnAssigned'
      const res = await $ajax.get(path, {
        params: {
          gmId: memId,
          state: 2
        }
      })
      if (res !== null && res.code != null && res.code === 200) {
        if (res.result.length === 0) {
          showSuccessMsg('无历史记录')
        } else {
          this.feedbackList = res.result
          showSuccessMsg('您共有' + res.result.length + '条历史记录')
        }
      } else {
        showErrorMsg('获取历史记录列表失败')
      }
    },
    async assignTask(afId, gmId) {
      const path = '/aqiFeedback/assign'
      const res = await $ajax.put(path, {
        afId,
        gmId
      })
      if (res !== null && res.code != null && res.code === 200) {
        showSuccessMsg('任务分配成功')
        await this.getAssignList()
      }
    },
    async getData(name) {
      // console.log(name)
      const path = '/aqiFeedback/select/count/province'
      const res = await $ajax.put(path, name)
      if (res !== null && res.code != null && res.code === 200) {
        return res.result
      }
      return null
    }
  }
})
